<?php
/**
 * Created by 七月.
 * Author: 七月
 * Date: 2017/6/1
 * Time: 17:08
 */

namespace app\api\service;


use app\api\model\MemberBill;
use app\api\model\Order as OrderModel;
use app\api\model\OrderBuy as OrderBuyModel;
use app\api\service\Order as OrderService;
use app\api\model\OrderRecharge as OrderRechargeModel;
use app\api\model\OrderAfterSale as OrderAfterSaleModel;
use app\api\model\OrderBuyAfterSale as OrderBuyAfterSaleModel;
use app\api\model\ErrorLog as ErrorLogModel;
use app\api\model\MemberBill as MemberBillModel;
use app\api\model\Member as MemberModel;
use app\api\model\Config as ConfigModel;
use app\lib\enum\OrderStatusEnum;
use app\lib\exception\OrderException;
use app\lib\exception\TokenException;
use Des3\DES3;
use think\Db;
use think\Exception;
use think\facade\Env;
use think\facade\Log;

//   extend/WxPay/WxPay.Api.php
include_once  __DIR__ . '/../../../extend/WxPay/WxPay.Api.php';

class Pay
{
    private $orderID;
    private $orderNO;
    private $tradeType;

    function __construct($orderID, $trade_type)
    {
        if (!$orderID)
        {
            throw new Exception('订单ID不允许为NULL');
        }
        if (!$trade_type)
        {
            throw new Exception('微信支付的支付方式不允许为空');
        }
        $this->orderID = $orderID;
        $this->tradeType = $trade_type;
    }

    /**
     * 订单支付
     * @return array
     */
    public function pay()
    {
        $this->orderNO = OrderService::makeOrderNo();
        echo md5('jgsdfjkfgjs#$%&khs2423hkfhget_order_info');exit;
        //订单号可能根本就不存在
        //订单号确实是存在的，但是，订单号和当前用户是不匹配的
        //订单有可能已经被支付过
        //进行库存量检测
//        $this->checkOrderValid();
//        $orderService = new OrderService();
//        $status = $orderService->checkOrderStock($this->orderID);
//        if (!$status['pass'])
//        {
//            return $status;
//        }
//        return $this->makeWxPreOrder($status['orderPrice'], $trade_type);
        return $this->makeWxPreOrder(0.1, $this->tradeType);
    }

    /**
     * 充值
     * @return array
     */
    public function rechargePay()
    {

        $this->orderNO = OrderService::makeOrderNo();

        //订单号可能根本就不存在
        //订单号确实是存在的，但是，订单号和当前用户是不匹配的
        //订单有可能已经被支付过
        //进行库存量检测
//        $this->checkOrderValid();
//        $orderService = new OrderService();
//        $status = $orderService->checkOrderStock($this->orderID);
//        if (!$status['pass'])
//        {
//            return $status;
//        }
//        return $this->makeWxPreOrder($status['orderPrice'], $trade_type);
        return $this->makeWxPreOrder(0.1, $this->tradeType);
    }

    private function makeWxPreOrder($totalPrice, $trade_type)
    {
        //openid
//        $openid = Token::getCurrentTokenVar('openid');
//        if (!$openid)
//        {
//            throw new TokenException();
//        }

//        $openid =

        $wxOrderData = new \WxPayUnifiedOrder();
        $wxOrderData->SetOut_trade_no($this->orderNO);
        $wxOrderData->SetTrade_type($trade_type);
        $wxOrderData->SetTotal_fee($totalPrice * 100);
        $wxOrderData->SetBody('零食商贩');
//        $wxOrderData->SetOpenid($openid);
        $wxOrderData->SetNotify_url(config('secure.pay_back_url'));
        return $this->getPaySignature($wxOrderData);
    }

    private function getPaySignature($wxOrderData)
    {
        $wxOrder = \WxPayApi::unifiedOrder($wxOrderData);
        if ($wxOrder['return_code'] != 'SUCCESS' ||
            $wxOrder['result_code'] != 'SUCCESS'
        )
        {
            Log::record($wxOrder, 'error');
            Log::record('获取预支付订单失败', 'error');
        }
        //prepay_id
        $this->recordPreOrder($wxOrder);
        $signature = $this->sign($wxOrder);
        return $signature;
    }

    private function sign($wxOrder)
    {
        $jsApiPayData = new \WxPayJsApiPay();
        $jsApiPayData->SetAppid(config('wx.app_id'));
        $jsApiPayData->SetTimeStamp((string)time());

        $rand = md5(time() . mt_rand(0, 1000));
        $jsApiPayData->SetNonceStr($rand);

        $jsApiPayData->SetPackage('prepay_id='.$wxOrder['prepay_id']);
        $jsApiPayData->SetSignType('md5');

        $sign = $jsApiPayData->MakeSign();
        $rawValues = $jsApiPayData->GetValues();
        $rawValues['paySign'] = $sign;

        unset($rawValues['appId']);

        return $rawValues;
    }

    private function recordPreOrder($wxOrder)
    {
        OrderModel::where('id', '=', $this->orderID)
            ->update(['prepay_id' => $wxOrder['prepay_id']]);
    }

    private function checkOrderValid()
    {
        $order = OrderModel::where('id', '=', $this->orderID)
            ->find();
        if (!$order)
        {
            throw new OrderException();
        }
        if (!Token::isValidOperate($order->user_id))
        {
            throw new TokenException(
                [
                    'msg' => '订单与用户不匹配',
                    'errorCode' => 10003
                ]);
        }
        if ($order->status != OrderStatusEnum::UNPAID)
        {
            throw new OrderException(
                [
                    'msg' => '订单已支付过啦',
                    'errorCode' => 80003,
                    'code' => 400
                ]);
        }
        $this->orderNO = $order->order_no;
        return true;
    }

    /**
     * 微信app端支付信息
     * @param $model
     * @param $id
     * @param $use_clothes_money
     * @return array
     * @throws OrderException
     */
    public static function wx_app_pay($model, $id, $use_clothes_money) {

        $uid = Token::getCurrentUid();

        switch ($model) {
            case 'order':
                $order = OrderModel::get(['id' => $id, 'member_id' => $uid]);
                break;
            case 'order_buy' :
                $order = OrderBuyModel::get(['id' => $id, 'member_id' => $uid]);
                break;
            case 'order_recharge':
                $order = OrderRechargeModel::get(['id' => $id, 'member_id' => $uid]);
                break;
            case 'order_buy_after_sale':
                $order = OrderBuyAfterSaleModel::get(['id' => $id, 'member_id' => $uid]);
                break;
            case 'order_after_sale':
                $order = OrderAfterSaleModel::get(['id' => $id, 'member_id' => $uid]);
                break;
            default:
                throw new OrderException([
                    'msg' => '订单模型错误',
                    'errorCode' => 60010
                ]);
        }
        try {
            if (!$order) {
                throw new OrderException();
            }

            if (in_array($model, ['order_buy_after_sale', 'order_after_sale'])){
                if ($order->status != 2) {
                    throw new OrderException([
                        'msg' => '订单不是待支付状态',
                        'errorCode' => 60011
                    ]);
                }
            } else {
                if ($order->status != 1) {
                    throw new OrderException([
                        'msg' => '订单不是待支付状态',
                        'errorCode' => 60011
                    ]);
                }
            }

            // 订单金额
            if (in_array($model, ['order_recharge', 'franchise_order'])) {
                $price = $order['money'];
            } else {
                $price = $order['price'];
            }

            // 如果是用了衣币支付，根据账户衣币计算剩余待支付金额
            if ($use_clothes_money && ($model == 'order' || $model == 'order_after_sale')) {
                $clothes_money = $order->orderMember->clothes_money_recharge + $order->orderMember->clothes_money_donate;
                $price = $clothes_money > $order->price ? 0 : $order->price - $clothes_money;
            }

            // 售后单支付时获取售后单号
            if ($model == 'order_buy_after_sale' || $model == 'order_after_sale') {
                $order_sn = $order['aftermarket_sn'];
            } else {
                $order_sn = $order['order_sn'];
            }

            // 测试阶段  支付金额设为0.01
//            $price = 0.01;

            /**
             * 微信支付附加数据
             */
            $des3 = new DES3();
            $attach['sign'] = $des3->encrypt('eybs');

            $notify_url = request()->domain() . "/index/pay/notify";

            $input = new \WxPayUnifiedOrder();
            $input->SetBody("衣依定制订单支付");
            $input->SetAttach(json_encode($attach)); // 商家数据包
            // $input->SetOut_trade_no(\WxPayConfig::MCHID.date("YmdHis"));//商户订单号
            $input->SetOut_trade_no($order_sn);
            $input->SetTotal_fee($price * 100); // 金额
            // $input->SetTotal_fee(1); //金额
//            $input->SetTime_start(date("YmdHis"));
//            $input->SetTime_expire(date("YmdHis", time() + 600));
            // $input->SetGoods_tag("test");
            $input->SetNotify_url($notify_url);
            $input->SetTrade_type("APP");

            // $input->SetOpenid($openId);
            $result = \WxPayApi::unifiedOrder($input);

            if(!array_key_exists("appid", $result)
                || !array_key_exists("prepay_id", $result)
                || $result['prepay_id'] == "")
            {
                throw new \WxPayException("参数错误:".json_encode($result) );
            }

            // 生成APP接口需要的数据
            $app_data = [
                'appid' => $result['appid'],
                'partnerid' => $result['mch_id'],
                'prepayid' => $result['prepay_id'],
                'package' => 'Sign=WXPay',
                'noncestr' => \WxPayApi::getNonceStr(),
                'timestamp' => time(),
            ];

            //签名步骤一：按字典序排序参数,并将参数按格式转化为字符串
            ksort($app_data);
            $buff = "";
            foreach ($app_data as $k => $v)
            {
                if($k != "sign" && $v != "" && !is_array($v)){
                    $buff .= $k . "=" . $v . "&";
                }
            }
            $buff = trim($buff, "&");

            //签名步骤二：在string后加入KEY
            $string = $buff . "&key=".\WxPayConfig::KEY;
            //签名步骤三：MD5加密
            $string = md5($string);
            //签名步骤四：所有字符转为大写
            $sign = strtoupper($string);

            $app_data['sign'] = $sign;


            // ③、在支持成功回调通知中处理成功之后的事宜，见 notify.php
            /**
             * 注意： 1、当你的回调地址不可访问的时候，回调通知会失败，可以通过查询订单来确认支付是否成功
             * 2、jsapi支付时需要填入用户openid，WxPay.JsApiPay.php中有获取openid流程 （文档可以参考微信公众平台“网页授权接口”， 参考http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html）
             */

            return $app_data;
        }
        catch (\Exception $e)
        {
            return ['code' => 400,'msg' => $e->getMessage()];
        }
    }

    /**
     * 支付回调业务处理
     * @param $order_price
     * @param $order_sn
     * @param $trade_no
     * @param $pay_type
     * @param $pay_desc
     * @return bool
     */
    public static function pay_notify($order_price, $order_sn, $trade_no, $pay_type, $pay_desc) {
        Db::startTrans();
        try {
            $order_data = [
                'pay_type' => $pay_type,
                'pay_sn' => $trade_no,
                'pay_time' => time()
            ];
            $order_model = substr($order_sn, 0, 2);
            if ($order_model == 'LT') {
                $sh_order_model = substr($order_sn, 0, 4); // 检查是否售后订单
                if ($sh_order_model == 'LTSH') {
                    // + ------  量体售后订单 ------ + //
                    self::ltsh_notify($order_sn, $order_price, $pay_desc, $order_data);
                } else {
                    // + ------  量体定制订单 ------ + //
                    self::lt_notify($order_sn, $order_price, $pay_desc, $order_data);
                }
            } else if ($order_model == 'XS') {
                $sh_order_model = substr($order_sn, 0, 4); // 检查是否售后订单
                if ($sh_order_model == 'XSSH') {
                    // + ------  商城售后订单 ------ + //
                    self::xssh_notify($order_sn, $order_price, $pay_desc, $order_data);
                } else {
                    // + ------  销售订单 ------ + //
                    self::xs_notify($order_sn, $order_price, $pay_desc, $order_data);
                }
            } else if ($order_model == 'CZ') {
                // + ------  充值订单 ------ + //
                self::recharge_notify($order_sn, $order_price, $pay_desc, $order_data);
            } else if ($order_model == 'TX') {
                // + ------  特许商城订单 ------ + //
                self::tx_notify($order_sn, $order_price, $pay_desc, $order_data);
            }
            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            file_put_contents(Env::get('root_path') . 'runtime/pay_error.txt', $e->getMessage() . " \n ", FILE_APPEND);
            // 回滚事务
            Db::rollback();
            return false;
        }
    }

    /**
     * 量体售后单回调业务处理
     * @param $order_sn
     * @param $order_price
     * @param $pay_desc
     * @param $order_data
     * @return bool
     */
    public static function ltsh_notify($order_sn, $order_price, $pay_desc, $order_data) {
        $order = OrderAfterSaleModel::get(['aftermarket_sn' => $order_sn]);
        if ($order->status != 2) {
            self::add_error_log('量体售后订单状态为' . $order['status'] . ',不是待付款状态', $order->aftermarket_sn);
            return false; // 订单不是待付款状态
        }

        // 如果订单金额不等于实际支付金额  返回false
        if ($order->price != $order_price) {
            self::add_error_log('量体售后订单实际支付金额为：' . $order_price . ',与待支付金额不相等', $order->aftermarket_sn);
            return false; // 订单不是待付款状态
        }

        // 补充订单数据
        $order_data['status'] = 3;
        $order->save($order_data);
        // 增加用户支付账单
        MemberBillModel::add_member_bill($order->member_id, $order_price, '售后单支付', 1, $order_sn, 'order_after_sale', $pay_desc, 3);
        return true;
    }

    /**
     * 量体单售后回调
     * @param $order_sn
     * @param $order_price
     * @param $pay_desc
     * @param $order_data
     * @return bool
     */
    public static function lt_notify($order_sn, $order_price, $pay_desc, $order_data) {
        $order = model('order')->get(['order_sn' => $order_sn]);
        if ($order['status'] != 1) {
            self::add_error_log('订单状态为' . $order['status'] . ',不是待付款状态', $order->order_sn);
            return false; // 订单不是待付款状态
        }

        // 如果支付金额低于订单金额  表示使用了衣币支付
        if ($order->price > $order_price) {
            self::clothes_money_pay($order, $order_price);
        }

        // 补充订单数据
        $order_data['status'] = 2;
        $order_data['pay_price'] = $order_price;
        if ($order->pattern_master_id > 0) {
            $order_data['status'] = 3;
            $order_data['pattern_master_receive_time'] = time();
        }
        model('order')->save($order_data, ['id' => $order->id]);
        // 增加用户支付账单
        MemberBill::add_member_bill($order->member_id, $order_price, '订单支付', 1, $order_sn, 'order', $pay_desc, 3);

        // 更新销量
//                    model('product')->where('id', $order->orderProduct->product_id)->setInc($order->orderProduct->num);

        $part_order_number = ConfigModel::get(['name' => 'order_inform_number']);
        $manage_mobile = $part_order_number['value'];
        // 短信通知
        $param = [
            'mobile' => $manage_mobile,
            'order_sn' => $order->order_sn,
            'linkman' => $order->consignee,
            'address_mobile' => $order->mobile,
            'address' => $order->province . $order->city . $order->area . $order->address,
            'type' => 8,
        ];
        NoteCode::send_code($param);
        return true;
    }

    /**
     * 销售售后单支付回调
     * @param $order_sn
     * @param $order_price
     * @param $pay_desc
     * @param $order_data
     * @return bool
     */
    public static function xssh_notify($order_sn, $order_price, $pay_desc, $order_data) {
        $order = model('order_buy_after_sale')->get(['aftermarket_sn' => $order_sn]);
        if ($order->status != 2) {
            self::add_error_log('商城售后订单状态为' . $order['status'] . ',不是待付款状态', $order->aftermarket_sn);
            return false; // 订单不是待付款状态
        }

        // 如果订单金额不等于实际支付金额  返回false
        if ($order->price != $order_price) {
            self::add_error_log('量体售后订单实际支付金额为：' . $order_price . ',与待支付金额不相等', $order->aftermarket_sn);
            return false; // 订单不是待付款状态
        }

        // 补充订单数据
        $order_data['status'] = 3;
        model('order_buy_after_sale')->save($order_data, ['id' => $order->id]);
        // 增加用户支付账单
        MemberBill::add_member_bill($order->member_id, $order_price, '售后单支付', 1, $order_sn, 'order_buy_after_sale', $pay_desc, 3);
        return true;
    }

    /**
     * 销售单支付回调
     * @param $order_sn
     * @param $order_price
     * @param $pay_desc
     * @param $order_data
     * @return bool
     */
    public static function xs_notify($order_sn, $order_price, $pay_desc, $order_data) {
        $order = model('order_buy')->get(['order_sn' => $order_sn]);
        if ($order['status'] != 1) {
            self::add_error_log('订单状态为' . $order['status'] . ',不是待付款状态', $order->order_sn);
            return false; // 订单不是待付款状态
        }

        // 补充订单数据
        $order_data['status'] = 2;
        $order_data['pay_price'] = $order_price;
        model('order_buy')->save($order_data, ['id' => $order->id]);

        if ($order->member_id == 180) {
            // 更新产品库存
            if($order->orderBuyProduct->product_attr_id > 0) {
                model('product_attr')->where('id', $order->orderBuyProduct->product_attr_id)->setDec('inventory', $order->orderBuyProduct->num);
            }
            // 更新销量
            model('product')->where('id', $order->orderBuyProduct->product_id)->setInc('sales', $order->orderBuyProduct->num);
        }

        // 增加用户支付账单
        MemberBill::add_member_bill($order->member_id, $order_price, '订单支付', 1, $order_sn, 'order_buy', $pay_desc, 3);

        $part_order_number = ConfigModel::get(['name' => 'order_inform_number']);
        $manage_mobile = $part_order_number['value'];
        // 短信通知
        $param = [
            'mobile' => $manage_mobile,
            'order_sn' => $order->order_sn,
            'linkman' => $order->consignee,
            'address_mobile' => $order->mobile,
            'address' => $order->province . $order->city . $order->area . $order->address,
            'type' => 9,
        ];
        NoteCode::send_code($param);

        return true;
    }

    /**
     * 充值订单回调
     * @param $order_sn
     * @param $order_price
     * @param $pay_desc
     * @param $order_data
     * @return bool
     * @throws \Exception
     */
    public static function recharge_notify($order_sn, $order_price, $pay_desc, $order_data) {
        $order = model('order_recharge')->get(['order_sn' => $order_sn]);
        if ($order['status'] != 1) {
            self::add_error_log('订单状态为' . $order['status'] . ',不是待付款状态', $order->order_sn);
            return false; // 订单不是待付款状态
        }

        // 补充订单数据
        $order_data['status'] = 2;
        model('order_recharge')->save($order_data, ['id' => $order->id]);

        // 更新用户充值衣币和业绩
        model('member')->where('id', $order->member_id)->setInc('clothes_money_recharge', $order_price);
        model('member')->where('id', $order->member_id)->setInc('performance', $order_price);

        // 增加用户充值账单
        MemberBill::add_member_bill($order->member_id, $order_price, '衣币充值', 2, $order_sn, 'order_recharge', $pay_desc, 2);

        // 充值成功立即结算
        $sub_account = \app\api\service\Order::sub_order_recharge_account($order->id);
        if ($sub_account['code'] == 0) {
            // 发送微信模板消息
            $data = ['touser' => 'o_WIcwccOaW-UdBrgeyDofcw5qO4',
                'template_id' => '-wjkS0vN_NOaiYY6biMRlySepDiPxzUu3TfcFb5FQnk',
                'topcolor' => '#FF0000',
                'data' =>
                    [
                        'first' => ['value' => '错误通知',"color" => "#173177"],
                        'keyword1' => ['value' => '充值单分账错误',"color" => "#173177"],
                        'keyword2' => ['value' => date('Y-m-d H:i:s'),"color" => "#173177"],
                        'remark' => ['value' => $sub_account['msg'],"color" => "#173177"]
                    ]
            ];
            send_wechat_tmplmsg(json_encode($data));
            throw new \Exception('充值订单分账错误:' . $sub_account['msg']);
        }

        return true;
    }

    /**
     * 特许商城支付售后
     * @param $order_sn
     * @param $order_price
     * @param $pay_desc
     * @param $order_data
     * @return bool
     */
    public static function tx_notify($order_sn, $order_price, $pay_desc, $order_data) {
        $order = model('franchise_order')->get(['order_sn' => $order_sn]);
        if ($order['status'] != 1) {
            self::add_error_log('订单状态为' . $order['status'] . ',不是待付款状态', $order->order_sn);
            return false; // 订单不是待付款状态
        }

        // 补充订单数据
        $order_data['status'] = 2;
        model('franchise_order')->save($order_data, ['id' => $order->id]);

        // 增加用户充值账单
        MemberBill::add_member_bill($order->member_id, $order_price, '特许商城订单支付', 1, $order_sn, 'franchise_order', $pay_desc, 3);
        return true;
    }

    /**
     * 订单部分衣币支付处理
     * @param $order
     * @param $order_price
     * @return bool
     */
    public static function clothes_money_pay($order, $order_price) {
        $clothes_money_recharge = $order->orderMember->clothes_money_recharge;
        $clothes_money_donate = $order->orderMember->clothes_money_donate;

        $clothes_money = $clothes_money_recharge + $clothes_money_donate;
        $pay_clothes_money = $order->price - $order_price;
        if ($clothes_money < $pay_clothes_money) {
            self::add_error_log('账户衣币不足', $order->order_sn);
            return false; // 账户衣币不足
        }

        if ($clothes_money_recharge >= $pay_clothes_money) { // 优先使用充值衣币
            model('member')->where('id', $order->member_id)->setDec('clothes_money_recharge', $pay_clothes_money);
            MemberBill::add_member_bill($order->member_id, $pay_clothes_money, '订单支付', 1, $order->order_sn, 'order', '充值衣币支付', 2);
        } else {
            // 充值衣币不足  将充值衣币清空， 在使用对应的赠送衣币完成支付
            $pay_clothes_money_donate = $pay_clothes_money - $clothes_money_recharge;
            $clothes_money_donate = $pay_clothes_money_donate - $clothes_money_donate;
            model('member')->save(['clothes_money_recharge' => 0, 'clothes_money_donate' => $clothes_money_donate], ['id' => $order->member_id]);
            if ($clothes_money_recharge > 0) {
                MemberBill::add_member_bill($order->member_id, $clothes_money_recharge, '订单支付', 1, $order->order_sn, 'order', '充值衣币支付', 2);
            }
            MemberBill::add_member_bill($order->member_id, $clothes_money_donate, '订单支付', 1, $order->order_sn, 'order', '赠送衣币支付', 2);
        }

        $order_data['pay_clothes_money'] = $pay_clothes_money;
        return true;
    }

    /**
     * 保存支付回调异常信息
     * @param $msg
     * @param $order_sn
     */
    public static function add_error_log($msg, $order_sn) {
        ErrorLogModel::create(['msg' => $msg, 'order_sn' => $order_sn]);
    }

    /**
     * 获取支付页面数据
     * @param $model
     * @param $order_id
     * @return array
     * @throws OrderException
     */
    public static function pay_data($model, $order_id) {
        $member_id = Token::getCurrentUid();

        $order = self::getOrderInfo($order_id, $model, $member_id);

        if ($model == 'order_after_sale' || $model == 'order_buy_after_sale') {
            if ($order->status != 2) {
                throw new OrderException('订单状态异常,不是待付款状态');
            }
        } else {
            if ($order->status != 1) {
                throw new OrderException('订单状态异常,不是待付款状态');
            }
        }

        $clothes_money = $deductible = $clothes_money = 0;  // 初始化
        $no_clothes_money_array = [
            'order_recharge','order_buy_after_sale','order_buy'
        ];
        if (!in_array($model, $no_clothes_money_array)) {
            $clothes_money = $order->orderMember->clothes_money_recharge + $order->orderMember->clothes_money_donate;
            $deductible = $clothes_money > $order->price ? $order->price : $clothes_money;
        }

        // 订单金额
        $price = $model == 'order_recharge' ? $order['money'] : $order['price'];

        // 售后单支付时获取售后单号
        if ($model == 'order_buy_after_sale' || $model == 'order_after_sale') {
            $order_sn = $order->aftermarket_sn;
        } else {
            $order_sn = $order->order_sn;
        }

        // TODO：当衣币大于0 的时候，前台可以选是否衣币支付
        // TODO：当选择使用衣币支付的时候，直接显示待支付金额即可
        // TODO：当选择衣币支付并且待支付金额为 0 的时候，请选择使用站内支付
        return $data = [
            'model' => $model, // 订单模型
            'order_id' => $order_id,   // 订单ID
            'order_sn' => $order_sn,    // 订单号
            'price' => $price,     // 订单金额
            'clothes_money' => $clothes_money,    // 衣币
            'deductible' => $deductible,   //  可减免的订单待支付金额（衣币数量 > 订单金额 ? 订单金额 : 衣币数量）
            'unpaid' => round($clothes_money > $price ? 0 : $price - $clothes_money, 2), // （待支付金额, 四舍五入  保留 两位小数）  说明:待支付金额为0 的时候，请调用站内支付方法
            'order_type' => get_order_type($model)  //  订单类型（中文）
        ];

    }

    /**
     * 衣币支付
     * @param $order_id
     * @param $model
     * @return bool
     * @throws Exception
     * @throws \Exception
     */
    public static function inStationPay($order_id, $model) {
        $member_id = Token::getCurrentUid();

        $order = self::getOrderInfo($order_id, $model, $member_id);

        $price = $order->price;
        Db::startTrans();
        try {
            MemberModel::clothesPayOrder($price, $member_id);

            if ($model == 'order') {
                $order_sn = $order->order_sn;
                $save_data = ['pay_type' => '衣币支付', 'pay_time' => time(), 'status' => 2];
                if ($order->pattern_master_id > 0) {
                    $save_data['status'] = 3;
                    $save_data['pattern_master_receive_time'] = time();
                }
                $order->save($save_data);
            } else if($model == 'order_after_sale') {
                $order_sn = $order->aftermarket_sn;
                $order->save(['pay_type' => '衣币支付', 'pay_time' => time(), 'status' => 3]);
            } else {
                throw new \Exception('订单类型异常');
            }
            MemberBill::add_member_bill($member_id, $price, '订单支付', 1, $order_sn, $model,  '衣币支付', 2);

            if ($order->pattern_master_id > 0) {
                // 微信消息通知量体师
                $data = [
                    'openid' => $order->orderPatternMaster->patternMasterMember->openid,
                    'first' => '发现新订单',
                    'url' => request()->domain() . url('index/pattern_master/info', ['id' => $order->id]),
                    'order_sn' => $order->order_sn,
                    'remark' => '系统自动分配定制订单，定制人：' . $order->consignee . " \n 联系电话：" . $order->mobile . " \n 联系地址：" . $order->province . $order->city . $order->area . $order->address . " \n 请尽快联系客户完成服务",
                ];
                send_wechat_tpl_by_status($data);
            } else {
                // 短信通知后台人员
                $part_order_number = ConfigModel::get(['name' => 'part_order_number']);  // 杨静秋
                $manage_mobile = $part_order_number['value'];
                $param = [
                    'mobile' => $manage_mobile,
                    'order_sn' => $order->order_sn,
                    'linkman' => $order->consignee,
                    'address_mobile' => $order->mobile,
                    'address' => $order->province . $order->city . $order->area . $order->address,
                    'type' => $model == 'order' ? 8 : 9
                ];
                NoteCode::send_code($param);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw $e;
        }

        return true;
    }


    /**
     * 获取订单信息
     * @param $order_id
     * @param $model
     * @param $member_id
     * @return null|\think\Model
     * @throws OrderException
     */
    private static function getOrderInfo($order_id, $model, $member_id) {
        $order_where = [
            'id' => $order_id, 'member_id' => $member_id
        ];

        switch ($model) {
            case 'order':
                $order = OrderModel::get($order_where);
                break;
            case 'order_buy' :
                $order = OrderBuyModel::get($order_where);
                break;
            case 'order_recharge':
                $order = OrderRechargeModel::get($order_where);
                break;
            case 'order_buy_after_sale':
                $order = OrderBuyAfterSaleModel::get($order_where);
                break;
            case 'order_after_sale':
                $order = OrderAfterSaleModel::get($order_where);
                break;
            default:
                throw new OrderException([
                    'msg' => '订单模型错误',
                    'errorCode' => 60010
                ]);
        }

        if (!$order) {
            throw new OrderException();
        }

        return $order;
    }
}